package cn.seaboot.word.html;

import cn.seaboot.html.HtmlReader;
import org.apache.poi.xwpf.usermodel.BodyElementType;
import org.apache.poi.xwpf.usermodel.IBodyElement;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFTable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.Writer;
import java.util.Iterator;

/**
 * body 迭代器内容读取
 * <p>
 * IBodyElement 是 Paragraph、Table 和 ContentControl 的统称
 * <p>
 * 其中，表格中可能会嵌套当前对象。
 *
 * @author Mr.css
 * @version 2025-06-26 14:37
 */
public class BodyReader implements HtmlReader<Iterator<IBodyElement>> {
    private final Logger logger = LoggerFactory.getLogger(BodyReader.class);

    /**
     * 结果写出
     */
    private final Writer writer;

    /**
     * 表格内容读取
     */
    private HtmlReader<XWPFTable> tableReader;

    /**
     * 段落内容读取
     */
    private HtmlReader<XWPFParagraph> paragraphReader;

    public BodyReader(Writer writer) {
        this.writer = writer;
    }

    public HtmlReader<XWPFTable> getTableReader() {
        return tableReader;
    }

    public void setTableReader(HtmlReader<XWPFTable> tableReader) {
        this.tableReader = tableReader;
    }

    public HtmlReader<XWPFParagraph> getParagraphReader() {
        return paragraphReader;
    }

    public void setParagraphReader(HtmlReader<XWPFParagraph> paragraphReader) {
        this.paragraphReader = paragraphReader;
    }

    @Override
    public void read(Iterator<IBodyElement> iterator) throws IOException {
        writer.write("<article>\r\n");
        while (iterator.hasNext()) {
            IBodyElement element = iterator.next();
            if (element.getElementType() == BodyElementType.PARAGRAPH) {
                paragraphReader.read((XWPFParagraph) element);
            } else if (element.getElementType() == BodyElementType.TABLE) {
                tableReader.read((XWPFTable) element);
            } else {
                // 估计是啥高级应用，普通文档没这东西，打个输出，等遇见了看看怎么个事儿
                logger.info("Using content control: {}", BodyElementType.CONTENTCONTROL);
            }
        }
        writer.write("</article>\r\n");
    }
}
